package com.example.code.photo;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 图片比较
 */
public class TestImageCompare {


    public static void main2(String[] args) {

        try {

            // 读取图片

            BufferedImage image1 = ImageIO.read(new File("E:\\screenRect2.png"));

            BufferedImage image2 = ImageIO.read(new File("E:\\screenRect_bubian.png"));


            // 转换成灰度图

            BufferedImage grayImage1 = toGray(image1);

            BufferedImage grayImage2 = toGray(image2);


            // 计算相似度

            double similarity = getSimilarity(grayImage1, grayImage2);

            System.out.println("Similarity: " + similarity);


        } catch (IOException e) {

            e.printStackTrace();

        }

    }
    // 转换成灰度图

    public static BufferedImage toGray(BufferedImage image) {

        int width = image.getWidth();

        int height = image.getHeight();

        BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

        for (int i = 0; i < width; i++) {

            for (int j = 0; j < height; j++) {

                int rgb = image.getRGB(i, j);

                grayImage.setRGB(i, j, rgb);

            }

        }

        return grayImage;

    }


    /**
     * 计算相似度
     */
    public static double getSimilarity(BufferedImage image1, BufferedImage image2) {

        int width = image1.getWidth();

        int height = image1.getHeight();

        int count = 0;

        double similarity = 0;

        for (int i = 0; i < width; i++) {

            for (int j = 0; j < height; j++) {

                int rgb1 = image1.getRGB(i, j);

                int rgb2 = image2.getRGB(i, j);

                if (rgb1 == rgb2) {

                    count++;

                }

            }

        }

        similarity = (double) count / (width * height);

        return similarity;

    }
}
